﻿using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using Core.Framework.Model.WebSockets;
using Core.Framework.Util;
using Core.Service.TaskHandle.Task_Model;

namespace Core.Service.TaskHandle.Task_Listener
{
    /// <summary>
    /// 二维码登录
    /// Template = WebSocketMidWare.Template
    /// [需保持一致]
    /// </summary>
    [Listenner(Template = "QRLogin")]
    public class QRLogin_Listener : BaseMQMsgListener, IMQMsgListener
    {
        public DoWork_Out DoWork(MessageQueue queue)
        {
            // 构造返回数据
            var outModel = new DoWork_Out
            {
                OK = false,
                Message = queue
            };

            try
            {

                // 获取消息组
                var channleHashName =$"_{queue.Message.Channel}";

                // *** 检查用户是否存在 ***
                if (!WebSocketApplication.ClientIdsPool.ContainsKey(channleHashName))
                {
                    // 提醒页面二维码过期
                    this.NotificationQRExpires(queue);
                    return outModel;
                }

                // 获取订阅客户端ID
                var ws = WebSocketApplication.ClientIdsPool[channleHashName];

                if (ws.State == WebSocketState.Open)
                {
                    // 构造发送消息
                    var json = this.StructureParameter(queue);
                    base.SendMessage(ws, json);
                    outModel.OK = true;
                }
                else
                {
                    // 提醒页面二维码过期
                    this.NotificationQRExpires(queue);
                }

                return outModel;
            }
            catch (Exception e)
            {
                outModel.Parameters = new object[] {e.Message };
                outModel.Action = "error";
                return outModel;
            }


        }

        /// <summary>
        /// 通知二维码过期
        /// </summary>
        public void NotificationQRExpires(MessageQueue queue)
        {
            // 客户ID组键值
            var clientHashName = WebSocketApplication.GetClientHashName(queue.ClientInfo);

            if (WebSocketApplication.ClientIdsPool.ContainsKey(clientHashName))
            {
                // 构造关联 客户端 键值队
                var ws = WebSocketApplication.ClientIdsPool[clientHashName];

                if (ws.State == WebSocketState.Open)
                    base.SendMessage(ws, new { type = "qrtimeout" }.TryToJson());
            }
        }

        public void Errer(DoWork_Out model)
        {
        }

        public void Success(DoWork_Out model)
        {
        }
    }
}
